package audio;

import java.io.File;
import java.io.IOException;

import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.LineEvent;
import javax.sound.sampled.LineListener;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.UnsupportedAudioFileException;



public abstract class SpotSound implements Sound {

	protected File soundFile;
	protected AudioInputStream audioInputStream = null;
	protected AudioFormat format;
	protected Clip clip = null;

	private LineListener listener = new LineListener() {

		@Override
		public void update(LineEvent event) {
			if (event.getType() == LineEvent.Type.START) {
				AudioManager.getSharedInstance().setPlayingSound(true);
			} else if (event.getType() == LineEvent.Type.STOP) {
				AudioManager.getSharedInstance().setPlayingSound(false);
			}
		}
	};


	protected void prepareAudioStream () throws IOException, UnsupportedAudioFileException, LineUnavailableException {
		audioInputStream = AudioSystem.getAudioInputStream(soundFile);

		format = audioInputStream.getFormat();
		DataLine.Info info = new DataLine.Info(Clip.class, format);
		clip = (Clip) AudioSystem.getLine(info);
		clip.addLineListener(listener);
	}



	@Override
	public float getLenght () {
		if (clip != null)
			return audioInputStream.getFrameLength()/format.getFrameRate();
		else
			return -1;
	}
	

	@Override
	public abstract void stopSound();

	@Override
	public void addListener (Object listener) {
		clip.addLineListener((LineListener) listener);
	}

}



